package com.android.fastride.activity.base;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;

import com.android.fastride.utils.StatusBarUtil;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.util.LinkedList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by admin on 2018/5/14.
 */

public class BaseActivity extends RxAppCompatActivity {
    protected Fragment fragment;

    //请求请求权限
    public static final int REQUEST_CODE_PERMISSION = 10020;

    /**
     * 绑定一个Fragment
     * 传入class，目的是自己创建，防止在面new的，在这里又没有使用，浪费内存。
     *
     * @param fragmentClz
     */
    protected void bindOneFragment(Class<? extends Fragment> fragmentClz) {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        Fragment oldFragment = supportFragmentManager.findFragmentById(android.R.id.content);
        if (oldFragment == null) {
            //通过反射调用空参构造方法
            try {
                fragment = fragmentClz.newInstance();
                supportFragmentManager.beginTransaction().add(android.R.id.content, fragment,
                        this.getClass().getName()).commit();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 绑定一个Fragment
     * 传入class，目的是自己创建，防止在面new的，在这里又没有使用，浪费内存。
     *
     * @param fragmentClz
     */
    protected void bindOneFragmentWithArgument(Class<? extends Fragment> fragmentClz,Bundle
            bundle) {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        Fragment oldFragment = supportFragmentManager.findFragmentById(android.R.id.content);
        if (oldFragment == null) {
            //通过反射调用空参构造方法
            try {
                fragment = fragmentClz.newInstance();
                fragment.setArguments(bundle);
                supportFragmentManager.beginTransaction().add(android.R.id.content, fragment,
                        this.getClass().getName()).commit();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setDarImagTextStatusBar();
        // 设置不可横屏切换
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 设置全屏显示
        setTransparentStatusBar();
    }

    private ViewGroup getRootView() {
        ViewGroup rootView = (ViewGroup) findViewById(android.R.id.content);
        return rootView;
    }

    public void setTransparentStatusBar() {
//        Build.VERSION_CODES.M
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

    }

    public void setDarImagTextStatusBar() {
        StatusBarUtil.StatusBarLightMode(this);
    }

    /**
     * app所需要的权限
     */
    private String[] permissionArray = new String[]{
            //SDK在Android 6.0下需要进行运行检测的权限如下：
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CALL_PHONE
    };

    /**
     * 请求权限
     */
    protected void requestPermission() {
        //根据不同的系统类型进行动态的授权
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //开始校验权限
            List<String> permissionList = new LinkedList<>();
            for (String permission : permissionArray) {
                int checkSelfPermission = ContextCompat.checkSelfPermission(this, permission);
                if (checkSelfPermission == PackageManager.PERMISSION_DENIED) {
                    permissionList.add(permission);
                }
            }
            //判断当前的是否还有没有授权的权限
            if (permissionList.isEmpty()) {
                onPermissionSuccess();
            } else {
                ActivityCompat.requestPermissions(this, permissionArray, REQUEST_CODE_PERMISSION);
            }
        } else {
            onPermissionSuccess();
        }
    }

    /**
     * App需要的所有权限，全部获取
     */
    protected void onPermissionSuccess() {
//        Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
        logIn();
    }

    protected void logIn() {

    }

    /**
     * App没有完整的权限，需进行相关的处理
     */
    protected void onPermissionFailure() {
        showGotoSettingPermissionDialog();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION:
                //判断所有的权限是不是已经授予了
                boolean hasPermission = true;
                for (int grantResult : grantResults) {
                    hasPermission = hasPermission && grantResult == PackageManager
                            .PERMISSION_GRANTED;
                }
                if (hasPermission) {
                    onPermissionSuccess();
                } else {
                    //判断能否再次询问一边
                    boolean canAskAgain = true;
                    for (int i = 0; i < permissions.length; i++) {
                        canAskAgain = canAskAgain && (grantResults[i] != PackageManager
                                .PERMISSION_DENIED || ActivityCompat
                                .shouldShowRequestPermissionRationale(this, permissions[i]));
                    }
                    if (canAskAgain) {
                        showRequestPermissionDialog();
                    } else {
                        onPermissionFailure();
                    }
                }
                break;
        }
    }

    private void showRequestPermissionDialog() {
        SweetAlertDialog.Builder builder = new SweetAlertDialog.Builder();
        builder.titleText("警告")
                .context(this)
                .type(SweetAlertDialog.NORMAL_TYPE)
                .contentText("此程序需要以下权限：\n" +
                        "1、存储权限\n" +
                        "2、获取通讯录权限\n" +
                        "3、读取本机识别码权限\n")
                .cancelable(false)
                .cancelOnTouchOutside(false)
                .cancelText("退出程序")
                .cancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        finish();
                    }
                })
                .confirmText("继续授权")
                .confirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        requestPermission();
                    }
                }).build().show();
    }

    /**
     * 到应用的设置页面
     *
     * @param context
     */
    public static void gotoAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings" +
                    ".InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context
                    .getPackageName());
        }
        context.startActivity(localIntent);
    }

    /**
     * 让用户去设置界面进行授权
     */
    private void showGotoSettingPermissionDialog() {
        SweetAlertDialog.Builder builder = new SweetAlertDialog.Builder();
        builder.context(this)
                .type(SweetAlertDialog.NORMAL_TYPE)
                .titleText("警告")
                .contentText("由于您禁止再次请求权限，所以只能到设置页面设置权限。")
                .cancelable(false)
                .cancelOnTouchOutside(false)
                .cancelText("退出程序")
                .cancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        finish();
                    }
                })
                .confirmText("去设置")
                .confirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        gotoAppDetailSettingIntent(sweetAlertDialog.getContext());
                    }
                }).build().show();
    }
}
